﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using hcms.Admin;
using hcom;
using System.Collections;
using System.Text.RegularExpressions;
using LitJson;

namespace hcms
{
	// 所有AJAX功能均在些，根据所取的内容不同，返回JSON格式和文本格式
	public partial class Ajax : System.Web.UI.Page
	{
		public Model model = Global.model;
		private dri8.local.lStr lstr = new dri8.local.lStr();
		private string cid, aid;
		private Hashtable json = new Hashtable();	// 用哈希表返回JSON数据

		protected void Page_Load(object sender, EventArgs e)
		{
			if (Request["titlelink"] != null)	// 移动版用标题取aid cid
			{
				// 从关联标题取aid,cid
				string strsql = string.Format(
					"select a.artID, b.acidColumnID from hcms_Articles as a inner join hcms_ArticleIDandColumnID as b " +
					"on a.artID = b.acidArticleID where a.artTitle = '{0}';",
					Request["titlelink"]
				);
				DataTable dt = model.da.GetTable(strsql);
				aid = dt.Rows[0][0].ToString();
				cid = dt.Rows[0][1].ToString();
			}
			else
			{
				// 从url中取cid, aid
				//"004-59779bb8-6bf5-4b95-a302-d41f0d1bea75-18.htm"
				string regex = @"(\d+)-(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})";
				Match match = Regex.Match(Request.UrlReferrer.LocalPath, regex);
				if (match.Success)	// 如果是文档从url中取cid, aid
				{
					cid = match.Result("$1");
					aid = match.Result("$2");
				}
			}

			// 取用户信息
			if (Request["getuserinfo"] != null)
				getuserinfo();


			// 参考文档
			if (Request["associate"] != null)
			{
				Hashtable associate = model.getAssociate(aid, cid, int.Parse(Request["associate"]));
				json.Add("associate", associate);
			}

			// 注册
			if (Request["register"] != null)
				register();

			// 登录
			if (Request["login"] != null)
			{
				Response.Write(model.Login(Request["login"], Request["password"], bool.Parse(Request["autologin"])));
			}

			// 注销
			if (Request["logout"] != null)
			{
				model.Logout();
				Response.Write("OK");
			}

			// 添加评论，放在取评论和取页数的前面，先加评论，再取评论和页数。
			if (Request["addcomment"] != null)
			{
				string textcmd = string.Format("hcms_spSaveComment '{0}', '{1}', '{2}', '{3}'",
					model.getNoteString("UserID"),
					Request["addcomment"].Replace("'", "''"),
					aid,
					Request.ServerVariables["REMOTE_ADDR"]
					);
				model.da.Execute(textcmd);
			}

			// 取评论
			if (Request["getcomments"] != null)
			{
				getcomments();
			}

			// 搜索
			if (Request["searchpage"] != null)
			{
				search();
			}

			// 我的帖子
			if (Request["myforum"] != null)
			{
				myforum();
			}

			// 记录当前文档点击数
			if (Request["clickarticle"] != null)
			{
				string strsql = string.Format("UPDATE hcms_Articles SET artClickCount = artClickCount + 1 WHERE artID='{0}'",
					aid);
				model.da.Execute(strsql);
			}

			// 发帖
			if (Request["addforumn"] != null)
			{
				Response.Write(saveforum());
			}

			// 输出到页面，如果json有内容，输出json数据，否则输出各段的Response.Write内容。
			if (json.Count > 0)
			{
				string str = JsonMapper.ToJson(json);
				Response.Write(str);
			}
		}

		/// <summary>
		/// 取用户信息，格式："userid|username|roles"，未登录返回unlogin
		/// </summary>
		void getuserinfo()
		{
			string str = "unlogin";
			if (HttpContext.Current.Request.IsAuthenticated) //已验证过
			{
				 str = model.getNoteString("UserID") + "|" + model.getNoteString("Username") + "|" + model.getNoteString("Roles");
			}
			json.Add("userinfo", str);
		}

		/// <summary>
		/// 保存贴子
		/// </summary>
		/// <returns>文档文件名称</returns>
		string saveforum()
		{
			string aid;
			if (Request["articoleid"] == null)	// 没有文章ID创建新贴子
			{
				// 保存文档
				aid = Guid.NewGuid().ToString();
				string strsql = string.Format("insert into hcms_Articles( artID, artTitle, " +
					"artContent, artUpdateTime, artUserID, artSource, artIP) " +
					"values('{{{0}}}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}');",
					aid,
					lstr.ToSQL(Request["addforumn"]),
					lstr.ToSQL(Request["content"]),
					DateTime.Now,
					model.getNoteString("UserID"),	// 保存用户ID
					lstr.ToSQL(Request["source"]),
					Request.ServerVariables["REMOTE_ADDR"]
					);
				model.da.Execute(strsql);
			}
			else
			{
				aid = Request["articoleid"];
				string strsql = string.Format("UPDATE hcms_Articles SET artTitle='{0}', " +
					"artContent='{1}', artUpdateTime='{2}', " +
					"artSource='{3}', artIP='{4}' " +
					" WHERE artID = '{5}'",
					lstr.ToSQL(Request["addforumn"]),
					lstr.ToSQL(Request["content"]),
					DateTime.Now,
					lstr.ToSQL(Request["source"]),
					Request.ServerVariables["REMOTE_ADDR"],
					aid
					);
				model.da.Execute(strsql);

				model.delFiles(aid); // 删除所有静态文档，有可能多个栏目包括该文档。
			}

			// 保存文档对应的栏目，可能是多个栏目。保存文档模板，便于打开文档时直接查找对应的模板
			string cid = Request["cid"];
			model.saveArticleCids(aid, cid);

			return cid + "-" + aid + ".htm";
		}

		/// <summary>
		/// 取评论
		/// </summary>
		private void getcomments()
		{
			string sqlstr = string.Format("hcms_spGetComment '{0}', {1}, {2}",
				aid,					// 文档ID
				Request["pagesize"],	// 每页行数
				Request["getcomments"]	// 页面号
				);
			DataSet ds = model.da.GetDataSet(sqlstr);
			int clickcount = (int)ds.Tables[0].Rows[0][0];		// 文档点击数
			DataTable dt = ds.Tables[1];						// 评论集
			int commentcount = (int)ds.Tables[2].Rows[0][0];	// 评论数
			//if (dt.Rows.Count == 0)
			//	throw (new Exception("不正确的文章ID")); //?? 加一个错误页，显示不同的异常。

			int n = dt.Rows.Count;
			string[,] arrComments = new string[n, 5];
			for (int i = 0; i < n; i++)
			{
				DataRow row = dt.Rows[i];
				arrComments[i, 0] = row["comFloor"].ToString();
				arrComments[i, 1] = ((DateTime)row["comDate"]).ToString("yyyy-MM-dd HH:mm");
				arrComments[i, 2] = lstr.getName(row["comIP"], row["userName"]);
				arrComments[i, 3] = row["userRoles"] == DBNull.Value ? "D" : row["userRoles"].ToString();
				arrComments[i, 4] = lstr.convertHtml(lstr.ToHtml((string)row["comComment"]));
			}

			int pagesize = int.Parse(Request["pagesize"]);	// 每页行数
			json.Add("comments", arrComments);
			json.Add("commentpages", (commentcount + pagesize - 1) / pagesize);
			json.Add("commentpagesize", Request["pagesize"]);
			json.Add("commentpage", Request["getcomments"]);
			json.Add("commentcount", commentcount);
			json.Add("clickcount", clickcount);
		}

		/// <summary>
		/// 搜索网站内容
		/// </summary>
		private void search()
		{
			// 取搜索参数
			int pagerows = 30;	// 每页行数，取不到参数时取30
			try { pagerows = int.Parse(Request["pagerows"]); }
			catch { }

			int page = 1;
			try { page = int.Parse(Request["searchpage"]) + 1; }
			catch { }	// page，取1

			int code = 0;
			try { code = int.Parse(Request.Cookies["searchcode"].Value); }
			catch { }	// 参数code不是整数时，取0

			// 从Cookie中取搜索内容，Cookie值在客户端点搜索时保存。
			string search = Request.Cookies["searchtext"] == null ? "" : Request.Cookies["searchtext"].Value;
			search = HttpUtility.UrlDecode(search);	// 解码
			search = HttpUtility.UrlDecode(search);	// ?? 不知道为什么要解两次

			// 如果没选范围时，算全选
			//if ((code & 0xC) == 0)
			//	code |= 0xC;
			if ((code & 0x3) == 0)
				code |= 0x3;

			// 建立SQL
			StringBuilder where1 = new StringBuilder(100);
			if ((code & 0xC) == 0x8)	// 只有文章
				where1.Append("AND (acidColumnID NOT LIKE '010%')");	// 排除论坛
			else if ((code & 0xC) == 0x4)	// 只有论坛
				where1.Append("AND (acidColumnID LIKE '010%')");	// 只选论坛

			StringBuilder where2 = new StringBuilder(200);
			if ((code & 0x2) != 0)	// 搜索标题
				where2.AppendFormat("(a.artTitle LIKE '%{0}%')", search);
			if ((code & 0x3) == 0x3)	// 搜索标题和内容
				where2.Append(" OR ");
			if ((code & 1) != 0)	// 搜索内容
				where2.AppendFormat("(a.artContent LIKE '%{0}%')", search);

			string strsql = string.Format(
				"SELECT COUNT(*) AS cnt " +
				"FROM hcms_Articles AS a INNER JOIN " +
					"(SELECT acidArticleID, acidColumnID " +
					"FROM hcms_ArticleIDandColumnID " +
					"WHERE (acidDeleted = 0) {0}) AS b ON a.artID = b.acidArticleID " +
				"WHERE {1}",
				where1,
				where2
			);
			int count = (int)model.da.ExecuteScalar(strsql);	// 总项数
			int pages = (count + pagerows - 1) / pagerows;		// 页数

			if (page > pages) page = pages;
			else if (page <= 0) page = 1;

			strsql = string.Format(
				"SELECT * " +
				"FROM (SELECT a.*, b.acidColumnID, ROW_NUMBER() OVER (ORDER BY a.artUpdateTime DESC) AS n " +
					"FROM hcms_Articles AS a INNER JOIN " +
						"(SELECT acidArticleID, acidColumnID " +
						"FROM hcms_ArticleIDandColumnID " +
						"WHERE (acidDeleted = 0) {0}) AS b ON a.artID = b.acidArticleID " +
					"WHERE {1}) AS c " +
				"WHERE n > {2} AND n <= {3}",	// 分页
				where1,
				where2,
				(page - 1) * pagerows,
				page * pagerows
			);
			DataTable dt = model.da.GetTable(strsql);

			int n = dt.Rows.Count;
			string[,] arrRows = new string[n, 4];
			for (int i = 0; i < n; i++)
			{
				DataRow row = dt.Rows[i];
				arrRows[i, 0] = ((DateTime)row["artUpdateTime"]).ToString("yyyy-MM-dd HH:mm");
				arrRows[i, 1] = row["acidColumnID"].ToString();
				arrRows[i, 2] = row["artID"].ToString();
				arrRows[i, 3] = row["artTitle"].ToString();
			}

			json.Add("rows", arrRows);
			json.Add("pages", pages);
			json.Add("pagerows", pagerows);
			json.Add("page", page);
			json.Add("count", count);
		}

		/// <summary>
		/// 我的帖子
		/// </summary>
		private void myforum()
		{
			// 取参数
			int pagerows = 30;	// 每页行数，取不到参数时取30
			try { pagerows = int.Parse(Request["pagerows"]); }
			catch { }

			int page = 1;
			try { page = int.Parse(Request["myforum"]) + 1; }
			catch { }	// page，取1

			int code = 0;
			try { code = int.Parse(Request.Cookies["searchcode"].Value); }
			catch { }	// 参数code不是整数时，取0

			// 从Cookie中取搜索内容，Cookie值在客户端点搜索时保存。
			string search = Request.Cookies["searchtext"] == null ? "" : Request.Cookies["searchtext"].Value;
			search = HttpUtility.UrlDecode(search);	// 解码
			search = HttpUtility.UrlDecode(search);	// ?? 不知道为什么要解两次

			// 如果没选范围时，算全选
			//if ((code & 0xC) == 0)
			//	code |= 0xC;
			if ((code & 0x3) == 0)
				code |= 0x3;

			// 建立SQL
			string strsql = string.Format(
				"SELECT COUNT(*) AS cnt " +
				"FROM hcms_Articles AS a INNER JOIN " +
					"(SELECT acidArticleID, acidColumnID " +
					"FROM hcms_ArticleIDandColumnID " +
					"WHERE (acidDeleted = 0) AND (acidColumnID LIKE '010%')) AS b ON a.artID = b.acidArticleID " +
				"WHERE artUserID = '{{{0}}}'",
				Context.User.Identity.Name
			);
			int count = (int)model.da.ExecuteScalar(strsql);	// 总项数
			int pages = (count + pagerows - 1) / pagerows;		// 页数

			if (page > pages) page = pages;
			else if (page <= 0) page = 1;

			strsql = string.Format(
				"SELECT * " +
				"FROM (SELECT a.*, b.acidColumnID, ROW_NUMBER() OVER (ORDER BY a.artUpdateTime DESC) AS n " +
					"FROM hcms_Articles AS a INNER JOIN " +
						"(SELECT acidArticleID, acidColumnID " +
						"FROM hcms_ArticleIDandColumnID " +
						"WHERE (acidDeleted = 0) AND (acidColumnID LIKE '010%')) AS b ON a.artID = b.acidArticleID " +
					"WHERE artUserID = '{{{0}}}') AS c " +
				"WHERE n > {1} AND n <= {2}",	// 分页
				Context.User.Identity.Name,
				(page - 1) * pagerows,
				page * pagerows
			);

			DataTable dt = model.da.GetTable(strsql);
			int n = dt.Rows.Count;
			string[,] arrRows = new string[n, 4];
			for (int i = 0; i < n; i++)
			{
				DataRow row = dt.Rows[i];
				arrRows[i, 0] = ((DateTime)row["artUpdateTime"]).ToString("yyyy-MM-dd HH:mm");
				arrRows[i, 1] = row["acidColumnID"].ToString();
				arrRows[i, 2] = row["artID"].ToString();
				arrRows[i, 3] = row["artTitle"].ToString();
			}

			json.Add("rows", arrRows);
			json.Add("pages", pages);
			json.Add("pagerows", pagerows);
			json.Add("page", page);
			json.Add("count", count);
		}

		private void register()
		{
			string str;
			str = string.Format("hcms_spRegister '{0}', '{1}', '{2}', '{3}', '{4}', '{5}'",
				Request["register"],
				Request["email"],
				Request["password"],
				Request.ServerVariables["REMOTE_ADDR"],
				"",	//Request["city"]
				"C4"	// 初始级别是C4，对应hcms_Users数据库表的Roles字段。
				);
			int r = model.da.Execute(str);
			if (r == -1)
			{
				Response.Write("用户名或邮箱重复");
				return;
			}

			Response.Write(model.Login(Request["register"], Request["password"], true));
		}




	}
}